import { Graph, Node } from '@antv/x6';
import { v4 as guid } from "uuid";
import { CellType, SiteOrientation } from '../enums';
import { FieldUpdatedEvent, SiteNodeConfig } from '../models';
import { cornerRadio } from './cornerRadio';
import { Constance } from './nodes-util';
import { Logger } from 'src/service/logger';

export class SiteNode extends Node {
  static ShapeName = "site";

  static register() {
    Graph.registerNode(SiteNode.ShapeName, SiteNode, true);
  }

  static unregister() {
    Graph.unregisterNode(SiteNode.ShapeName);
  }

  static getMeta(cfg?: SiteNodeConfig): Node.Metadata {
    const { site: _size } = Constance.sizes;
    const size = { width: cfg?.Width ?? _size.width, height: cfg?.Height ?? _size.height };
    const position = { x: cfg?.X ?? 0, y: cfg?.Y ?? 0 };

    const config: SiteNodeConfig = {
      Id: cfg?.Id ?? guid(),
      Name: cfg?.Name ?? "点位",
      Width: size.width,
      Height: size.height,
      X: position.x,
      Y: position.y,
      Orientation: cfg?.Orientation ?? SiteOrientation.Horizontal,
      ParentId: cfg?.ParentId ?? "",
      Fields: cfg?.Fields ?? [],
      Status: cfg?.Status ?? {
        Id: guid(),
        Name: "Status",
        Description: "点位状态",
        FontSize: 12,
        Visible: true,
        Maps: []
      },
      Type: CellType.Site
    };

    const meta = {
      shape: SiteNode.ShapeName,
      size,
      position,
      id: config.Id,
      label: config.Name,
      attrs: {
        body: {
          stroke: '#8f8f8f',
          strokeWidth: 1,
          fill: '#fff',
          ...cornerRadio
        },
        title: {
          text: config.Name,
        }
      },
      data: {
        cfg: config,
      },
      zIndex: 2,
    };
    return meta;
  }

  update(cfg: SiteNodeConfig) {
    this.attr("title/text", cfg.Name);
    const img = cfg.Orientation == SiteOrientation.Horizontal ? '/assets/images/nodes/ladder-h.png' : '/assets/images/nodes/ladder-v.png';
    this.attr("image/xlink:href", img);
    this.data.cfg = cfg;
  }

  fieldValueUpdated(e: FieldUpdatedEvent) {
    const { cfg }: { cfg: SiteNodeConfig; } = this.data;
    this.data.Values = e.Values;
    const statusVal = e.Values["Status"];
    const status = cfg.Status.Maps.find(a => a.Key == statusVal);
    if (status) {
      const color = status.Color;
      this.attr("status/fill", color);
      this.attr("status/text", `状态：${status.Description}`);
    } else {
      const color = "red";
      this.attr("status/fill", color);
      this.attr("status/text", `状态：${statusVal}`);
    }

    const Barcode = e.Values["Barcode"];
    if (Barcode) {
      this.attr("tray/visibility", "visible");
    } else {
      this.attr("tray/visibility", "hidden");
    }
    const content = cfg.Fields.filter(a => a.Visible).map(f => `${f.Description ?? f.Name}:  ${e.Values[f.Name] ?? ""}`)
      .reduce((r, str) => r + "\n" + str, "");
    this.attr("info/text", content);
  }

  getConfig(): SiteNodeConfig {
    const { x, y } = this.position();
    const { width, height } = this.size();
    const cfg: SiteNodeConfig = {
      ...this.data.cfg,
      ParentId: this.getParentId(),
      Id: this.id,
      X: x,
      Y: y,
      Width: width,
      Height: height,
      Type: CellType.Site,
    };
    return cfg;
  }

  logger?: Logger;
  setLogger(logger: Logger) {
    this.logger = logger;
  }

  bindPositionAndSizeChange() {
    this.on("change:position", ({ current }) => {
      const cfg = {
        ...this.data.cfg,
        X: current?.x,
        Y: current?.y
      };
      this.data.cfg = cfg;
    });
    this.on("change:size", ({ current }) => {
      const cfg = {
        ...this.data.cfg,
        Width: current?.width,
        Height: current?.height
      };
      this.data.cfg = cfg;
    });
  }
}

SiteNode.config(
  {
    width: 200,
    height: 60,
    markup: [
      {
        tagName: 'rect',
        selector: 'body',
      },
      {
        tagName: 'image',
        selector: 'image',
      },
      {
        tagName: "image",
        selector: "tray",
      },
      {
        tagName: 'text',
        selector: 'title',
      },
      {
        tagName: 'text',
        selector: 'status',
      },
      {
        tagName: 'text',
        selector: 'info',
      },
    ],
    attrs: {
      // body: {
      //   fill: 'rgba(255,255,255,0.3)',
      //   refWidth: 1,
      //   refHeight: 1,
      // },
      image: {
        xlinkHref: '/assets/images/nodes/ladder-h.png',
        refWidth: 1.3,
        refHeight: 1.3,
        opacity: 0.8,
        filter: {
          name: 'dropShadow',
          args: {
            dx: 1,
            dy: 1,
            blur: 1,
          },
        },
      },
      tray: {
        xlinkHref: '/assets/images/nodes/tray.png',
        refWidth: 0.8,
        refHeight: 0.8,
        refX: 0.1,
        refY: 0.1,
        opacity: 1,
        visibility: 'hidden',
        filter: {
          name: 'dropShadow',
          args: {
            dx: 2,
            dy: 2,
            blur: 3,
          },
        },
      },
      title: {
        text: '点位',
        class: 'text-shadow-1',
        refX: 0,
        refY: 0,
        y: -8,
        fontSize: 14,
        fill: "#fff",
        textAnchor: 'start',
      },
      status: {
        text: '状态',
        class: 'text-shadow-1',
        refX: 10,
        refY: 10,
        fontSize: 14,
        fill: 'white',
        textAnchor: 'start',
      },
      info: {
        text: '',
        class: 'text-shadow-1',
        refX: 10,
        refY: 20,
        fontSize: 12,
        fill: 'white',
        'textAnchor': 'start',
      },
    },
  }
);